﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Collections.ObjectModel;
using System.ServiceModel.DomainServices.Client;
using C1.Silverlight.DataGrid.Summaries;

namespace DYSales.Views.Stock
{
    public partial class Inventory_page : Page
    {
        public Inventory_page()
        {
            InitializeComponent();
            dg_pds.AutoGeneratingColumn += dg_pds_未盘_AutoGeneratingColumn;
            dg_pds_已盘.AutoGeneratingColumn += dg_pds_未盘_AutoGeneratingColumn;
            Loaded += new RoutedEventHandler(Inventory_page_Loaded);
            tb_数量.AddHandler(KeyDownEvent, new KeyEventHandler(tb_数量_KeyDown), true);
            bt_初始化盘点.Click += new RoutedEventHandler(bt_初始化盘点_Click);
            bt_执行盘点.Click += new RoutedEventHandler(bt_执行盘点_Click);
            tb_快速查询.AddHandler(KeyDownEvent, new KeyEventHandler(tb_快速查询_KeyDown), true);
        }

        void tb_快速查询_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && tb_快速查询.Text != string.Empty)
            {
                var pds = dm.getDS().PdTables.Where(p => p.p_条形码.Equals(tb_快速查询.Text));
                if (pds.Count() == 1)
                {
                    tb_数量.Value = Convert.ToDouble(pds.First().p_库存数量);
                    tb_数量.Focus();
                }
                else if (pds.Count() > 1)
                {
                    dg_pds.DataContext = null;
                    dg_pds.DataContext = pds;
                }
                else
                {
                    tb_快速查询.Text = string.Empty;
                    tb_快速查询.Focus();
                }
            }
        }

        void bt_执行盘点_Click(object sender, RoutedEventArgs e)
        {
            var box = other.GetMessageBox();
            box.Title = "执行盘点";
            box.tbk_text.Text = "执行此操作将会把未盘点商品删除，将已盘点商品数量更改为盘点后数量，是否继续？";
            box.Closed += new EventHandler(box1_Closed);
            box.Show();
        }

        void box1_Closed(object sender, EventArgs e)
        {
            var box = sender as cwin_Question;
            box.Closed -= new EventHandler(box1_Closed);
            if (box.DialogResult.Value)
            {
                dm.getDS().Load(dm.getDS().GetPdTablesQuery(), LoadBehavior.RefreshCurrent, lo =>
                {
                    var pdits = dg_pds_已盘.DataContext as IEnumerable<Web.PdInventory>;
                    foreach (var item in dm.getDS().PdTables.ToList())
                    {
                        var pd = pdits.FirstOrDefault(p => p.p_商品名称.Equals(item.p_商品名称));
                        if (pd != null)
                        {
                            item.p_库存数量 = pd.p_盘点数量;
                        }
                    }
                    dm.getDS().GetST(lt => {
                        foreach (var item in dm.getDS().PdInventories.ToList())
                        {
                            var ip = new Web.Inventory();
                            ip.p_操作员 = item.p_操作员;
                            ip.p_单价 = item.p_单价;
                            ip.p_库存数量 = item.p_库存数量;
                            ip.p_盘点结果 = item.p_盘点结果;
                            ip.p_盘点日期 = lt.Value;
                            ip.p_盘点数量 = item.p_盘点数量;
                            ip.p_拼音简码 = item.p_拼音简码;
                            ip.p_商品编号 = item.p_商品编号;
                            ip.p_商品名称 = item.p_商品名称;
                            ip.p_条形码 = item.p_条形码;
                            dm.getDS().Inventories.Add(ip);
                            dm.getDS().PdInventories.Remove(item);
                        }
                        dm.getDS().SubmitChanges(le =>
                        {
                            pds_not.Clear();
                            refresh();
                        }, null);
                    }, null);
                }, null);
            }
        }

        void bt_初始化盘点_Click(object sender, RoutedEventArgs e)
        {
            var box = other.GetMessageBox();
            box.Title = "盘点";
            box.tbk_text.Text = "执行此操作将会把当前已盘点的数据清空，是否继续？";
            box.Closed += new EventHandler(box_Closed);
            box.Show();
        }

        void box_Closed(object sender, EventArgs e)
        {
            var box = sender as cwin_Question;
            box.Closed -= new EventHandler(box_Closed);
            if (box.DialogResult.Value)
            {
                foreach (var item in dm.getDS().PdInventories.ToList())
                {
                    dm.getDS().PdInventories.Remove(item);
                }
                dm.getDS().SubmitChanges(lo => { refresh(); }, null);
            }
        }

        void tb_数量_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                AddLP();
            }
        }

        void AddLP()
        {
            if (tb_快速查询.Text != string.Empty)
            {
                var pds = dm.getDS().PdTables.Where(p => p.p_条形码.Equals(tb_快速查询.Text));
                if (pds.Count() == 1)
                {
                    var pd = pds.First();
                    save(pd);
                }
                else if (pds.Count() > 1)
                {
                    if (dg_pds.Selection.SelectedRows.Count == 1)
                    {
                        var pd = dg_pds.Selection.SelectedRows.First().DataItem as Web.PdTable;
                        if (pd != null)
                        {
                            tb_数量.Value = Convert.ToDouble(pd.p_库存数量);
                            save(pd);
                        }
                    }
                }
                else
                {
                    takeSum();
                }
            }
        }

        void save(Web.PdTable pd)
        {
            var pdit = CreateLP(pd);
            var lp = dm.getDS().PdInventories.FirstOrDefault(p => p.p_商品编号.Equals(pd.p_商品编号));
            if (lp == null)
            {
                dm.getDS().PdInventories.Add(pdit);
            }
            else
            {
                lp.p_盘点数量 = (decimal)tb_数量.Value;
                lp.p_库存数量 = pd.p_库存数量;
                lp.p_盘点结果 = pdit.p_盘点数量 - pdit.p_库存数量;
            }
            dm.getDS().SubmitChanges(lo =>
            {
                tb_快速查询.Text = string.Empty;
                localRefresh();
            }, null);
        }

        Web.PdInventory CreateLP(Web.PdTable pd)
        {
            var pdit = new Web.PdInventory();
            pdit.p_单价 = pd.p_单价;
            pdit.p_拼音简码 = pd.p_拼音简码;
            pdit.p_商品编号 = pd.p_商品编号;
            pdit.p_商品名称 = pd.p_商品名称;
            pdit.p_盘点数量 = (decimal)tb_数量.Value;
            pdit.p_库存数量 = pd.p_库存数量;
            pdit.p_盘点结果 = pdit.p_盘点数量 - pdit.p_库存数量;
            pdit.p_条形码 = pd.p_条形码;
            return pdit;
        }

        void dg_pds_未盘_AutoGeneratingColumn(object sender, C1.Silverlight.DataGrid.DataGridAutoGeneratingColumnEventArgs e)
        {
            if (e.Property.PropertyType.Equals(typeof(decimal)) || e.Property.PropertyType.Equals(typeof(double)))
            {
                e.Column.Format = "0.##";
            }
            if (e.Property.PropertyType.Equals(typeof(DateTime)))
            {
                e.Column.Format = "yyyy/MM/dd HH:mm:ss";
            }
            #region 减少列
            string headername = e.Column.Header.ToString();
            switch (headername)
            {
                case "ID":
                case "库存下限":
                case "进货价":
                    e.Cancel = true;
                    break;

                case "库存数量":
                    DataGridAggregate.SetAggregateFunctions(e.Column, new DataGridAggregatesCollection { new DataGridAggregateSum() });
                    break;
                case "盘点数量":
                    DataGridAggregate.SetAggregateFunctions(e.Column, new DataGridAggregatesCollection { new DataGridAggregateSum() });
                    break;
                case "盘点结果":
                    DataGridAggregate.SetAggregateFunctions(e.Column, new DataGridAggregatesCollection { new DataGridAggregateSum() });
                    break;
            }
            #endregion
        }

        void Inventory_page_Loaded(object sender, RoutedEventArgs e)
        {
            pds_not = new ObservableCollection<Web.PdTable>();
            refresh();
        }

        void localRefresh()
        {
            dg_pds_已盘.DataContext = dm.getDS().PdInventories;
            foreach (var item in dm.getDS().PdTables)
            {
                if (dm.getDS().PdInventories.FirstOrDefault(p => p.p_商品编号.Equals(item.p_商品编号)) == null)
                {
                    pds_not.Add(item);
                }
            }
            takeSum();
        }

        ObservableCollection<Web.PdTable> pds_not;
        void refresh()
        {
            dm.getDS().Load(dm.getDS().GetPdInventorysQuery(), LoadBehavior.RefreshCurrent, lo =>
            {
                dg_pds_已盘.DataContext = lo.Entities;
                dm.getDS().Load(dm.getDS().GetPdTablesQuery(), LoadBehavior.RefreshCurrent, le =>
                {
                    takeSum();
                }, null);
            }, null);
        }

        void takeSum()
        {
            tbk_仓库商品数量.Text = (dm.getDS().PdTables.Count() - dm.getDS().PdInventories.Count()).ToString();
            tbk_仓库商品未盘库存数量.Text = (dm.getDS().PdTables.Sum(p => p.p_库存数量) - dm.getDS().PdInventories.Sum(p => p.p_盘点数量)).ToString();
            dg_pds_已盘.Refresh();
            tb_快速查询.Focus();
            tb_数量.Value = 0;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

    }
}
